Skip to content

Resample host memory after flushing CUDA cache in CompilePool - #641

Open
nero- wants to merge 1 commit into
NVIDIA:mainfrom
nero-:fix/compile-pool-empty-cache
Open

nero- wants to merge 1 commit into
NVIDIA:mainfrom
nero-:fix/compile-pool-empty-cache

Conversation

@nero-

@nero- nero- commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Why this change is needed and why this approach

Before this change, compiler_resources() in ignition/preparation/compile_pool.py sampled host_memory.available_bytes() before calling torch.cuda.empty_cache(). On integrated/unified-memory GPUs (such as NVIDIA GB10), PyTorch's CUDA caching allocator holds physical host RAM, so flushing cached segments increases both device_memory_info() and host_memory.available_bytes(). Because available was never resampled after torch.cuda.empty_cache(), the subsequent available = min(available, free) discarded every byte reclaimed by the flush and kept the stale pre-flush host memory reading.

In addition, the flush trigger only checked free - headroom_bytes < device_bytes, skipping torch.cuda.empty_cache() both when unified-memory admission was bounded by the higher host compiler headroom/worker budget (max(_HEADROOM_BYTES, headroom_bytes) + worker_bytes) and when a discrete GPU's free memory fell below the admissible worker cap (max_workers * device_bytes). Finally, in ForwardCache._prepare_ranks(), release_unused() ran before dist.barrier(group=group) without torch.cuda.empty_cache(), so peer ranks sharing a host could sample host memory before other ranks returned cached CUDA segments.

Flushing cached CUDA segments before sampling—and resampling both free and available after a flush on unified memory—fixes the stale memory accounting without relaxing headroom invariants or worker memory budgets.

What changed

  • ignition/preparation/compile_pool.py: extracted _DEFAULT_MAX_WORKERS = 8, clamped available = min(available, free) once when shared is True, triggered torch.cuda.empty_cache() whenever available - headroom < max_workers * worker_bytes (on unified memory) or free - headroom_bytes < max_workers * device_bytes (on discrete GPUs), and resampled both free and available after flushing on unified memory (while leaving discrete GPUs to resample only free).
  • ignition/preparation/aot.py: added torch.cuda.empty_cache() immediately after release_unused() inside the existing try/except block preceding dist.barrier(group=group) in ForwardCache._prepare_ranks(), preserving barrier progress and collective error reporting on failure.
  • tests/preparation/test_compile_pool.py: added CPU unit tests covering unified-memory resampling across reclamation thresholds (POSIX and Windows via host_memory.os), discrete-GPU worker-capacity recovery (default and explicit compile_workers > 8), no-flush skips when memory already covers max_workers, and _prepare_ranks() flush-before-barrier ordering on both success and failure.

Claimed benefit

Unified-memory and multi-rank preparations accurately account for freed PyTorch CUDA cache segments when budgeting forward compiler workers, preventing spurious MemoryError failures under tight physical memory and unlocking additional compiler workers when cached segments would otherwise cap admission.

Supporting evidence and material limitations

  • CPU unit tests: CUDA_VISIBLE_DEVICES="" pytest -q tests/preparation/test_compile_pool.py tests/preparation/test_capture_order.py tests/preparation/test_forward_artifact_sharing.py tests/preparation/test_transient_retention.py tests/preparation/test_host_memory.py passed (160 passed, 0 failed).
  • Live 3-node SM121 (3× NVIDIA GB10, 121.7 GiB unified memory) before/after validation: Exporting DeepSeek-V4.1-Flash-1017 at TP3 (--ranks 3 --gpus 0 --max-concurrency 16 --mtp-draft-tokens 5 --prefill-chunk-size 6144 --image-concurrency 4 --expert-scale-compression csf --draft-head-quantization nvfp4 --markov-head-quantization fp8 --vocabulary-parallel-sampling --row-shard-prefill --row-shard-attention, paired with Pass candidate GPUs into filter_world_sizes during planning #635 and Enable cross-host SM121 RoCE TP3 for DeepSeek V4.1 local-inference-lab/hyperflare-recipes#103):
    • Before: Failed at Compile model forwards in 2.5s with MemoryError: host ... has 51 missing forwards but no capacity for a forward compiler (8435 MiB available host memory, 8192 MiB headroom) while ~4.9 GiB of freed preparation tensors remained in PyTorch's caching allocator.
    • After: Identical export admitted 3 compiler workers ([1, 1, 1]), compiled 51/51 forwards cleanly (1204.2s, 11.0–11.3 GiB MemAvailable with active compiler workers), captured all 193/193 CUDA graphs (804 MiB free at final graph, 97.66 GiB fixed GPU/rank), and passed flare run qualification (24/24 determinism 0.0000 nats KL, 23/24 top-1 vs TP4 0.0424 nats KL, -1.4593 NLL, 3.965s cold 32K needle pass, 61/61 concurrency, 4/4 concurrent image probe pass).
  • Material limitations: Windows unified-memory behavior is validated via CPU unit tests mocking host_memory.os.name == "nt" and torch.cuda.mem_get_info rather than live Windows hardware.

Discord: nero

Before this change, `compiler_resources()` in `ignition/preparation/compile_pool.py`
sampled `host_memory.available_bytes()` before calling `torch.cuda.empty_cache()`.
On integrated/unified-memory GPUs (such as NVIDIA GB10), PyTorch's CUDA caching
allocator pins physical host RAM, so flushing cached segments increases both
`device_memory_info()` and `host_memory.available_bytes()`. Because `available`
was never resampled after `torch.cuda.empty_cache()`, the subsequent
`available = min(available, free)` discarded every byte reclaimed by the flush
and kept the stale pre-flush host memory reading. In addition, the flush trigger
only checked `free - headroom_bytes < device_bytes`, skipping `empty_cache()`
both when unified-memory admission was bounded by the higher host compiler
headroom/worker budget and when a discrete GPU's free memory fell below the
admissible worker cap (`max_workers * device_bytes`). Finally, in
`ForwardCache._prepare_ranks()`, `release_unused()` ran before the resource
collection barrier without `torch.cuda.empty_cache()`, so peer ranks sharing a
host could sample `available_bytes()` before other ranks returned cached CUDA
segments.

Flushing cached CUDA segments before sampling—and resampling both `free` and
`available` after a flush on unified memory—solves the false `MemoryError`
without relaxing memory budgets, headroom invariants, or worker sizing limits.

In `ignition/preparation/compile_pool.py`, extracted `_DEFAULT_MAX_WORKERS = 8`,
clamped `available = min(available, free)` once when `shared` is `True`,
triggered `torch.cuda.empty_cache()` whenever `available - headroom < max_workers
* worker_bytes` (on unified memory) or `free - headroom_bytes < max_workers *
device_bytes` (on discrete GPUs), and resampled both `free` and `available`
after flushing on unified memory (while leaving discrete GPUs to resample only
`free`). In `ignition/preparation/aot.py`, added `torch.cuda.empty_cache()`
immediately after `release_unused()` inside the existing `try/except` block
preceding `dist.barrier(group=group)` in `ForwardCache._prepare_ranks()`. In
`tests/preparation/test_compile_pool.py`, added CPU unit tests covering unified
memory resampling across reclamation thresholds (POSIX and Windows), discrete
GPU worker-capacity recovery (default and explicit `compile_workers > 8`),
no-flush skips when memory already covers `max_workers`, and `_prepare_ranks()`
flush-before-barrier ordering on both success and failure.

Unified-memory and multi-rank preparations now account for freed PyTorch CUDA
cache segments when budgeting forward compiler workers, preventing spurious
`MemoryError` failures under tight physical memory and unlocking multi-worker
admission when cached segments would otherwise cap worker counts.

Validated with CPU unit tests (`CUDA_VISIBLE_DEVICES="" pytest -q
tests/preparation/test_compile_pool.py tests/preparation/test_capture_order.py
tests/preparation/test_forward_artifact_sharing.py
tests/preparation/test_transient_retention.py
tests/preparation/test_host_memory.py`: 160 passed, 0 failed). Validated
end-to-end on 3x NVIDIA GB10 (121.7 GiB unified memory) exporting
`DeepSeek-V4.1-Flash-1017` at TP3 (`--prefill-chunk-size 6144 --row-shard-prefill
--row-shard-attention --image-concurrency 4 --max-concurrency 16
--mtp-draft-tokens 5 --vocabulary-parallel-sampling`): before this change,
`Compile model forwards` failed in 2.5s with `MemoryError (8435 MiB available
host memory, 8192 MiB headroom)`; after this change, the identical export
admitted 3 compiler workers (`[1, 1, 1]`), compiled 51/51 forwards (1204.2s,
11.0-11.3 GiB `MemAvailable` with active compiler workers), captured all
193/193 CUDA graphs (804 MiB free at final graph), and passed `flare run`
qualification (24/24 determinism 0.0000 nats KL, 23/24 top-1 vs TP4 0.0424 nats
KL, -1.4593 NLL, 3.965s cold 32K needle pass, 61/61 concurrency, 4/4 concurrent
image probe pass). Limitation: Windows unified-memory behavior is verified via
CPU unit tests mocking `host_memory.os.name == "nt"` and `torch.cuda.mem_get_info`
rather than live Windows hardware.

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Jonathan Gutierrez <phialpha0@gmail.com>
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 641.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added area:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. area:preparation Ignition checkpoint loading, tuning, compilation, capture, and export. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 30, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

PR #641 cleanly fixes a verified memory-accounting bug in compiler_resources() and a peer-rank flush ordering gap in ForwardCache._prepare_ranks() without relaxing any headroom invariant, worker budget, or artifact/API contract. Only minor optional simplifications and confirming .github/workflows/python-cpu.yml (not opened) CI is green on d82fcfc remain.

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 2 · Nits: 2
Walkthrough
  • ignition/preparation/compile_pool.py:26: Extracts _DEFAULT_MAX_WORKERS = 8 from the previous inline literal.
  • ignition/preparation/compile_pool.py:46-64: Computes worker_bytes, headroom, and max_workers ahead of sampling; clamps available = min(available, free) before the flush check when shared is true; triggers torch.cuda.empty_cache() when available - headroom < max_workers * worker_bytes (integrated) or free - headroom_bytes < max_workers * device_bytes (discrete); and resamples both free and available = min(host_memory.available_bytes(), free) after flushing on unified memory (while resampling only free on discrete GPUs).
  • ignition/preparation/aot.py:1068-1074: Calls torch.cuda.empty_cache() immediately after release_unused() inside the existing try/except block preceding dist.barrier(group=group) in ForwardCache._prepare_ranks(), ensuring peer ranks on a shared host flush cached CUDA segments before any rank samples host memory.
  • tests/preparation/test_compile_pool.py:538-683: Adds well-isolated pytest monkeypatch unit tests covering POSIX and Windows (os.name == "nt") unified-memory host resampling across reclamation thresholds, discrete-GPU capacity recovery (default and explicit compile_workers > 8), flush skipping when memory already covers max_workers, and _prepare_ranks() release_unused -> empty_cache -> barrier -> compiler_resources ordering on both success and failure.
Merge Risk: Low · up to d82fcfc
  • Scoped to one-shot forward-compilation worker admission (ignition/preparation/compile_pool.py:38-64, ignition/preparation/aot.py:1068-1074); serving hot paths, CUDA graph capture contracts, CompilerResources fields, allocate_workers() admission math (compile_pool.py:67-98), and exported core formats are untouched.
  • Multi-rank synchronization and failure propagation remain deadlock-free: torch.cuda.empty_cache() runs inside the existing try/except ahead of dist.barrier(group=group) (aot.py:1068-1074), so any flush failure is folded into error and surfaced collectively after all_gather_object(demand, ...) (aot.py:1081-1085, 1130-1131).
  • Discrete-GPU and Windows (os.name == "nt") paths are validated by mocked CPU unit tests rather than live hardware (disclosed in the PR description), and .github/workflows/python-cpu.yml (not opened) CI has not yet reported a run on d82fcfc.
Pre-merge checks: ✅ 2 passed · ⚠️ 1 warnings
  • ✅ Security / malicious screen: Pure Python preparation and test changes across 3 files; no prompt injection, shell execution, credential handling, or unsafe deserialization introduced.
  • ✅ Charter & value fit: Fixes a reproducible physical-memory accounting defect in shared ignition/preparation/ code with no new flags, env vars, dependencies, or per-model branches, directly aligned with docs/preparation-development.md:305-318 and SM121/GB10 goals.
  • ⚠️ Related / duplicate / conflict check: Clean against main (no conflicting commits since base) and disjoint from open Ready-To-Merge PR Key compiled forward sharing and Inductor validation by GPU name #597 (allocate_workers / GPU-name keying). Open draft PR ignition: tune discrete CompilePool sizing and scale Inductor compile threads #639 (currently Changes Requested with 2 blockers) edits compiler_resources() and lowers _DISCRETE_WORKER_DEVICE_BYTES to 704 << 20, which would conflict with the 1 GiB discrete expectations in tests/preparation/test_compile_pool.py:608-610; whichever lands second will need a rebase.
  • ⚠️ Tests & verification evidence: Author reports 160 passed, 0 failed on 5 targeted preparation test files plus a live 3-node SM121 (3× GB10) before/after export + flare run qualification (explicitly noting paired branches #635 and hyperflare-recipes#103, which are orthogonal to memory resampling). Confirm .github/workflows/python-cpu.yml (not opened) (.venv/bin/python -m pytest tests/ -q, .github/workflows/python-cpu.yml:30-33 (not opened)) is green on d82fcfc before merging; discrete-GPU, >1-worker-per-host, and Windows paths are CPU-mock-only.

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. area:preparation Ignition checkpoint loading, tuning, compilation, capture, and export. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants